package com.mk.seckill.config;

import com.mk.seckill.pojo.User;
import com.mk.seckill.service.IUserService;
import com.mk.seckill.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author hhwu
 * @Description //TODO 自定义用户参数
 * @Date 13:19 2022/6/7
 **/
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
	@Autowired
	private IUserService userService;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		/**
		 * @Author hhwu
		 * @Description //TODO 如果该方法返回true，才会执行下面的resolveArgument方法
		 * @Date 13:21 2022/6/7
		 * @Param [parameter]
		 * @return boolean
		 **/
		Class<?> clazz = parameter.getParameterType(); // 获取参数类型
		return clazz == User.class;// 如果输入的参数是User类型时，才执行判断
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
	                              NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		/**
		 * @Author hhwu
		 * @Description //TODO 判断用户是否存在的逻辑，返回用户对象
		 * @Date 13:35 2022/6/7
		 * @Param [parameter, mavContainer, webRequest, binderFactory]
		 * @return java.lang.Object
		 **/
//		// 判断ticket是否为空，返回user对象
//		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
//		String ticket = CookieUtil.getCookieValue(request, "userTicket");
//		if (StringUtils.isEmpty(ticket)) {
//			return null;
//		}
//		return userService.getUserByCookie(ticket, request, response);// 从redis中返回ticket对应的user对象

		// 在拦截器中已经将user信息写入了threadlocal中，这里可以直接从threadlocal中获取
		return UserContext.getUser();
	}
}